package com.nercel.dsj.gksales.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * @author sunlin
 * @date 2019-4-8
 */
public class SafeBase64 {

	public static String safeUrlBase64Encode(String data){
		String encodeBase64 = new BASE64Encoder().encode(data.getBytes());
		String safeBase64Str = encodeBase64.replace('+', '-');
		safeBase64Str = safeBase64Str.replace('/', '_');
		safeBase64Str = safeBase64Str.replaceAll("=", "");
		safeBase64Str = safeBase64Str.replaceAll("\r\n", "");
		return safeBase64Str;
	}


	public static String safeUrlBase64Decode(final String safeBase64Str){
		String base64Str = safeBase64Str.replace('-', '+');
		base64Str = base64Str.replace('_', '/');
		int mod4 = base64Str.length()%4;
		if(mod4 > 0){
			base64Str = base64Str + "====".substring(mod4);
		}
		try {
			return new String(new BASE64Decoder().decodeBuffer(base64Str));
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}

	}



}
